package http_proxy

import (
	"errors"
	"gitee.com/dennis-kk/service-box-go/util/slog"
	"github.com/gin-gonic/gin"
	"net"
	"net/http"
	"net/http/httputil"
	"os"
	"strings"
)

func httpProxyWithLogger(logger slog.BoxLogger) gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				var brokenPipe bool
				// 网络异常需要处理
				if ne, ok := err.(*net.OpError); ok {
					var se *os.SyscallError
					if errors.As(ne, &se) {
						if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
							brokenPipe = true
						}
					}
				}

				if logger != nil {
					httpRequest, _ := httputil.DumpRequest(c.Request, false)
					headers := strings.Split(string(httpRequest), "\r\n")
					for idx, header := range headers {
						current := strings.Split(header, ":")
						if current[0] == "Authorization" {
							headers[idx] = current[0] + ": *"
						}
					}
					if brokenPipe {
						logger.Error("%s\n%s", err, string(httpRequest))
						c.Error(err.(error))
						c.Abort()
					} else {
						logger.Error("[Recovery] error %s", err)
						c.AbortWithStatus(http.StatusInternalServerError)
					}

				}
			}
		}()
		c.Next()
	}
}
